package com.ant.myagile


import grails.converters.JSON
import grails.plugins.springsecurity.Secured

import java.text.DateFormat
import java.text.ParseException
import java.text.SimpleDateFormat

import org.springframework.security.authentication.ProviderManager
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
import org.springframework.security.core.Authentication
import org.springframework.security.core.AuthenticationException
import org.springframework.security.core.context.SecurityContextHolder

import com.ant.myagile.utils.CommonUtils

class TeamController {
	TeamService teamService

	def loginService
	/**
	 * Dependency injection for the authenticationTrustResolver.
	 */
	def springSecurityService

	ProviderManager authenticationManager;

	@Secured([
		'ROLE_USER',
		'ROLE_ADMIN',
		'ROLE_GUEST'
	])
	def index(){
		redirect(action:"myTeams" )
	}
	def saveTeam(){
		Member owner = springSecurityService.currentUser
		def teamName = params.teamName
		def mailGroup =  params.mailGroup
		def description =  params.description
		def establishedDate =  params.establishedDate
		Date date;
		if(establishedDate.toString() != ""){
			try{
				DateFormat formatter;
				formatter = new SimpleDateFormat("yyyy-MM-dd");
				date = (Date) formatter.parse(establishedDate+"")
			}catch(ParseException ex){
				ex.printStackTrace();
			}
		}else{
			date = null;
		}
		def projects = params.list('myCheckbox')
		def team = teamService.save_Team(teamName, mailGroup, description, date, projects, owner)
		def file = request.getFile("image")

		if(!file.empty){
			def webRootDir = servletContext.getRealPath("/")
			def userDir = new File(webRootDir,"images/teamLogo")
			userDir.mkdirs();
			file.transferTo(new File(userDir,file.originalFilename))
			team.logo = file.originalFilename
			team.save()
		}
		if(team){
			redirect(uri:"/team/myTeams/"+ team.id)
		}
	}
	@Secured([
		'ROLE_USER',
		'ROLE_ADMIN',
		'ROLE_GUEST'
	])
	def myTeams(Long id){
		Member member = springSecurityService.currentUser
		def ownerId = member.id
		if(member==null){
			redirect(action:"auth",controller:"login")
		}
		def team;

		if (id) team = Team.get(id)

		params.max = Math.min(params.max ? params.int('max') : 3, 100)
		params.sort = "teamName"
		params.order = "asc"
		List<Team> teams = teamService.getAllTeamByUser(ownerId)

		if(teams.size() == 0){
			flash.message = "List of Team is empty!"
			return [projects: teamService.projectsOfMember(ownerId), roles: member.getAuthorities().authority]
		}
		team=Tracking.findByMember(member)?.team
		if(team==null){
			team=teams.get(0)
		}
		def projListInProgress =  teamService.projInProgress(team)

		[team : team, projListInProgress: projListInProgress,  projects: teamService.projectsOfMember(ownerId), members: team.teamMembers, teams : teams, roles: member.getAuthorities().authority]
	}

	def updateTeam(){
		def teamId = params.teamId
		def t = Team.get(teamId)
		def teamName = params.teamName
		def mailGroup = params.mailGroup
		def description = params.description
		def establishedDate = params.establishedDate
		Date date;
		if(establishedDate.toString() != ""){

			try{
				DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
				date = (Date) formatter.parse(establishedDate+"")
			}catch(ParseException  ex){
				ex.printStackTrace();
			}
		}else{
			date = null;
		}
		def newProjects =  new ArrayList<Long>();
		def deletedProjects = new ArrayList<Long>();
		def existProjects = new ArrayList<Long>();


		def checkedProjects = params.list('myCheckbox')

		def assignedProjIdList = new ArrayList<Long>();
		assignedProjIdList = teamService.assignedProjIdList(t)
		if(assignedProjIdList){

			for(i in assignedProjIdList){
				if(teamService.checkIdInList(checkedProjects, i)== true){
					existProjects.add(i)
				}
			}


			for(i in assignedProjIdList){
				if(teamService.checkIdInList(checkedProjects, i) == false){
					deletedProjects.add(i)
				}
			}

			for(i in checkedProjects){
				if(teamService.checkIdInList(assignedProjIdList, i) == false){
					newProjects.add(i)
				}
			}
		}
		else{
			for(i in checkedProjects){
				newProjects.add(i)
			}
		}


		Team newTeam = teamService.updateTeam(teamName, mailGroup, description, date, teamId, newProjects,existProjects, deletedProjects)

		def file = request.getFile('image')
		if(!file.empty){
			def webRootDir = servletContext.getRealPath("/")
			def userDir = new File(webRootDir,"images/teamLogo")
			userDir.mkdirs();
			file.transferTo(new File(userDir,file.originalFilename))
			newTeam.logo = file.originalFilename
			newTeam.save()
		}
		redirect(uri:"/team/myTeams/"+ teamId)
	}

	def deleteTeam(){
		def teamId = params.teamId
		Team t = teamService.getTeamById(teamId)
		teamService.deleteTeam(t)
		List<Team> teams = teamService.getAllTeamByUser()
		if(teams.size() == 0){
			redirect(uri:"/team/myTeams/")
			flash.message = "No Team"
		}else{
			redirect(uri:"/team/myTeams/"+ teams[0].id)
		}
	}

	def getTeamInfo() {
		def teamInfo = teamService.getTeamById(request.getParameter("teamId"));
		def projInProgress = teamService.projInProgress(teamInfo)
		def date
		if(teamInfo.establishedDate != null){
			date = teamInfo.establishedDate.format("yyyy-MM-dd")
		}else{
			date = null
		}
		render([team: teamInfo, establishedDate: date, assignedProjList : projInProgress] as JSON)
		response.status = 200
	}


	def getMember(){
		def teamId=params.teamId
		def members=Team.get(teamId).teamMembers
		render (template:'memberDetail',model:[members : members])
	}

	def memberOfTeam(){
		Member member = springSecurityService.currentUser
		def teamId=params.teamName;
		def trackUpdate;
		if((trackUpdate=Tracking.findByMember(member))!=null) {
			trackUpdate.team=Team.get(teamId)
			trackUpdate.save(failOnError:true)
		}
		else{
			Tracking track=new Tracking()
			track.member=member
			track.team=Team.get(teamId)
			try{
				track.save(failOnError:true)
			}catch(Exception e){
			}
		}
		if(params.teamName=='null'||Team.get(teamId)==null) {
			render (template:'detail',model:[members : null])
		}
		else {
			Team team = Team.get(teamId)
			def team_member=Team_Member.findByTeam(team)			
			render (template:'detail',model:[members : team.teamMembers,team:team, projListInProgress: teamService.projInProgress(team)])
		}
	}

	static allowedMethods = [active: "GET"]
	def activeError(){
	}
	def active() {
		// Active user
		println params.tk
		def tm=Team_Member.findByToken(params.tk)
		if(tm!=null)
		{

			def today=new Date()
			def datetoken=tm.tokenDate
			if((today.getTime()-datetoken.getTime())>(2*24*60*60*1000))
			//			if((today.getTime()-datetoken.getTime())>(1000))
			{
				// Token is timeout
				tm.delete()
				Member m=Member.get(tm.member.id)
				m.delete()
				redirect (action : "activeError")


			}
			else{
				// token valid
				flash.valid="1"// Member not actived
				tm.member.isActive = true
				tm.isAccepted=true
				tm.token=""
				tm.save(flush:true)
				Member m=Member.get(tm.memberId)
				m.enabled=true;
				m.save(flush:true)
				try {
					UsernamePasswordAuthenticationToken usernameAndPassword = new UsernamePasswordAuthenticationToken(m.username,"")
					Authentication auth = authenticationManager.doAuthentication(usernameAndPassword);
					SecurityContextHolder.getContext().setAuthentication(auth);
				}
				catch(AuthenticationException e){
					SecurityContextHolder.getContext().setAuthentication(null);
					log.error("Login failed after registration. This should never happen: ", e);
				}
				redirect (uri:"/team/myTeams/"+tm.teamId)
			}
		}
		else{
			redirect (action : "activeError")
		}
	}
	def checkExistTeamMember(String email, long id){
		def check=Team_Member.findAll(){member==Member.findByUsername(email); team == Team.get(id)}
		if(check.size()>0)
		{
			return true
		}
		return false
	}
	def sendMailActive(params){
		String success="<div style=\"color: blue;\">"
		String fail="<div style=\"color: red;\">"
		String path=new MailService().realPath(servletContext);
		long teamId = Long.parseLong(params.teamId+"")
		flash.sendResult=""
		String listmail=params.txaMemberList.trim().toLowerCase()

		def mails=listmail.split(";")
		Set set = new HashSet();
		for ( mailmember in mails) {
			set.add(mailmember)
		}

		for ( mailmember in set) {

			if(!checkExistTeamMember(mailmember, teamId)){
				MailService m=new MailService()
				MailService mail=new MailService()

				def tk= m.createAutoNumber()
				try{
					String content= "<p>You had been added to team</p>"+
                                                        "<hr>"+
                                                        "<p><a href=\"${path}Team/active?tk="+tk+"\">Click here</a> to accept!</p>"
					mail.sendMail("Active your account",content,mailmember)
				}catch(Exception e){

					continue;
				}
				Member member=new Member(username:mailmember, password:"")
				try{
					member.save(flush:true);
					def userRole = Role.findByAuthority("ROLE_USER") ?: new Role(authority: "ROLE_USER").save(failOnError: true)
					if (!member.authorities.contains(userRole)) {
						MemberRole.create member, userRole
					}

				}catch(Exception ex){
					println ex
				}
				Team_Member team_member=new Team_Member()
				team_member.member=Member.findByUsername(mailmember)
				team_member.with {
					team=Team.get(params.teamId)
					token=tk
					tokenDate=new Date()

				}
				try{
					team_member.save(failOnError:true)
					flash.sendResult+="${success}${mailmember} was send successfully</div>"
				}catch(Exception e){
					println e
				}
			}else{
				flash.sendResult+="${fail}${mailmember} was added to this team before</div>"
			}


		}
		render ([result:flash.sendResult] as JSON)
	}

	def jsonFindTeamByProject() {
		def pid = request.getParameter("projectID");
		def teams = teamService.findTeamByProject(pid);
		if(teams) {
			render(contentType: 'text/json', {[teams : teams, result : 'OK']});
			response.status = 200;
		} else {
			render(contentType: 'text/json', {[result : 'No Data']});
			response.status = 200;
		}
	}

	def removeMemberFromTeam(params){
		def teamId =  params.teamId
		def memberId =  params.memberId
		def result = 'success'
		if (teamService.removeMemberFromTeam(teamId, memberId)){}
		else result = 'fail'
		render ([result: result] as JSON)
	}

	def changePosition(params){
		def teamId =  params.teamId
		def memberId =  params.memberId
		def position =  params.position
		teamService.changePosition(teamId, memberId, position)
		render ([result: 'success'] as JSON)
	}
}
